"""
API场景组合测试工具 - 模板服务
"""
import json
import requests
from app.models.environment import Environment

class TemplateService:
    """模板服务，用于获取模板数据"""
    
    def get_template_data(self, template_id, env_config):
        """获取模板数据"""
        # 获取查询服务配置
        query_service = env_config.get('query_service', {})
        url = query_service.get('url', '')
        method = query_service.get('method', 'POST')
        headers = query_service.get('headers', {})
        
        # 构建请求体
        body = {
            'template_id': template_id
        }
        
        # 添加额外参数
        extra_params = query_service.get('extra_params', {})
        body.update(extra_params)
        
        # 发送请求
        try:
            response = requests.request(
                method=method,
                url=url,
                headers=headers,
                json=body,
                timeout=30
            )
            
            # 检查响应状态
            if response.status_code != 200:
                raise Exception(f'模板数据查询失败: {response.status_code} {response.text}')
            
            # 解析响应
            try:
                response_data = response.json()
            except:
                response_data = {'text': response.text}
            
            # 提取数据
            data_path = query_service.get('data_path', '')
            if data_path:
                data = self._extract_value(response_data, data_path)
            else:
                data = response_data
            
            return data
        except Exception as e:
            raise Exception(f'获取模板数据失败: {str(e)}')
    
    def _extract_value(self, data, path):
        """从数据中提取值"""
        if not path:
            return data
        
        parts = path.split('.')
        current = data
        
        for part in parts:
            if isinstance(current, dict) and part in current:
                current = current[part]
            else:
                return None
        
        return current